import { router, addRoutes } from '@/router'
import { getToken } from '@/composables/auth'
import { toast } from '@/composables/util'
import { useUserStore } from '@/store'
import { WHITE_LIST, LAYOUT_PATH, PROJECT_NAME } from '@/config/settings'
import nprogress from 'nprogress'

nprogress.configure({
  showSpinner: false
})

// 标记是否已获取用户信息
let hasUserInfo = false
// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  // 开启加载进度条
  nprogress.start()
  // 获取 token
  const token = getToken()
  // 没有登录，强制跳转至登录页
  // if (!token && to.path != '/login') {
  // if (!token && !WHITE_LIST.includes(to.path)) {
  if (!token && to.path != WHITE_LIST[0]) {
    toast('请先登录', 'error')
    // return next({ path: '/login' })
    // return next({ path: WHITE_LIST })
    return next({ path: WHITE_LIST[0] })
  }
  // 阻止重复登录
  // if (token && to.path == '/login') {
  // if (token && WHITE_LIST.includes(to.path)) {
  if (token && to.path === WHITE_LIST[0]) {
    toast('您已登录，请勿重复登录', 'error')
    // return next({ path: from.path ? from.path : '/' })
    return next({ path: from.path ? from.path : LAYOUT_PATH })
  }
  let hasNewRoutes = false
  // 用户登录了，自动获取用户信息并存储至pinia
  if (token && !hasUserInfo) {
    const userStore = useUserStore()
    const { menus } = await userStore.getInfo()
    hasUserInfo = true
    hasNewRoutes = addRoutes(menus)
  }
  hasNewRoutes ? next(to.fullPath) : next()
})

// 后置守卫
router.afterEach(to => {
  // 关闭加载动画
  nprogress.done()
  // 将路由元信息赋值到浏览器标题
  // document.title = `${to.meta.title || ''} | CMS后台管理系统`
  document.title = `${to.meta.title || ''} | ${PROJECT_NAME}`
})